package p.ithorns.tools.log;

import ch.qos.logback.classic.Logger;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 代理日志工厂类
 */
public final class LogProxyFactory {
    public static LogProxy getProxy(Class<?> cls) {
        try {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(LogProxy.class);
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                    Field nameField = Logger.class.getDeclaredField("FQCN");
                    Field modifiersField = Field.class.getDeclaredField("modifiers");
                    modifiersField.setAccessible(true);
                    modifiersField.setInt(nameField, nameField.getModifiers() & ~Modifier.FINAL);
                    nameField.setAccessible(true);
                    nameField.set(null, cls.getName());
                    Object result = proxy.invokeSuper(obj, args);
                    nameField.set(null, Logger.class.getName());
                    return result;
                }
            });
            return (LogProxy) enhancer.create();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new LogProxy();
    }
}


